import java.util.StringTokenizer;
/**
 * 
 */

/**
 * Breaks a String separated by spaces into two types of tokens , numbers and operators.
 * @author Michael Fildestine ID:309161594
 *
 */
public class ExpTokenizer extends StringTokenizer{
	
	
	 
	public ExpTokenizer(String exp) { 
		    super(exp); 
	}
	/**
	 * @return BinaryOp if next element is and operand else returns ValueToken
	 */
	public Object nextElement(){ 
		//if the next token is one of the operands we return the operand , else it's a number and we return a ValueToken 
		  CalcToken resultToken = null; 
		  String token =  super.nextToken(); 
		  if (token.equals("+")) { 
		      resultToken =  new AddOp(); 
		  } else if (token.equals("*")){ 
		      resultToken =  new MultiplyOp(); 
		  } else if (token.equals("/")){ 
		      resultToken =  new DivideOp();
		  } else if (token.equals("-")){
		      resultToken =  new SubtractOp();
		  } else if (token.equals("^")){ 
		      resultToken =  new PowOp();    
		  }	else if (token.equals("(")){
			  resultToken = new OpenBracket();
		  } else if (token.equals(")")){
			  resultToken = new CloseBracket();
		  } else if (legalDouble(token)){   
		      resultToken = new ValueToken(Double.parseDouble(token)); 
		  } else{
			  throw new ParseException("SYNTAX ERROR:" + token ); //in case the syntax is not correct
		  }
		   return resultToken;   
		} 
	
	/**
	 * Checks if a given string is a legal double value;
	 * @param token
	 * @return True if the string is a legal double expression, returns false otherwise.
	 */
	private boolean legalDouble (String token){
		boolean ans = true;
		int decimalNum = 0;
		
		for (int i = 0 ; i < token.length() && decimalNum <=1 && ans; i++){
			if (token.charAt(i) == '.'){
				decimalNum++;
			}else if (!(token.charAt(i) >= '0' && token.charAt(i) <= '9')){
				
				ans = false;
			}
			
		}
		return ans && (decimalNum <= 1);
	}

}
